let events = [];
let currentFilter = '';

        // 页面加载完成后初始化
        document.addEventListener('DOMContentLoaded', function() {
            console.log('dispatch.html 页面开始加载...');
            console.log('AuthManager 是否存在:', !!window.AuthManager);
            
            // 等待认证管理器初始化
            const checkAuth = () => {
                console.log('dispatch.html: 检查AuthManager初始化');
                if (window.AuthManager) {
                    console.log('dispatch.html: AuthManager已初始化，开始初始化页面');
                    initPage();
                } else {
                    console.log('dispatch.html: AuthManager未初始化，等待...');
                    setTimeout(checkAuth, 100);
                }
            };
            checkAuth();
        });

        function initPage() {
            console.log('dispatch.html: 开始初始化页面');
            
            // 使用AuthManager的认证检查，与其他页面保持一致
            if (!window.AuthManager || !AuthManager.isAuthenticated()) {
                console.log('dispatch.html: 用户未认证，跳转到登录页');
                window.location.href = '/ercms/login';
                return;
            }
            
            console.log('dispatch.html: 认证检查通过，开始初始化页面功能');
            
            // 显示用户信息
            displayUserInfo();
            
            // 初始化页面功能
            loadEvents();
            loadStatistics();
            loadNotifications();
            setInterval(function() {
                loadEvents();
                loadStatistics();
                loadEventMarkers(); // 定时刷新地图标记
            }, 10000);
            
            // 初始化地图
            if (window.AMap) {
                var map = new AMap.Map('dispatchMap', {
                    zoom: 11,
                    center: [116.397428, 39.90923]
                });
                
                // 正确加载地图控件
                AMap.plugin(['AMap.Scale', 'AMap.ToolBar'], function() {
                    map.addControl(new AMap.Scale());
                    map.addControl(new AMap.ToolBar());
                });
                
                // 存储地图实例供其他函数使用
                window.dispatchMap = map;
                
                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(function(position) {
                        var lng = position.coords.longitude;
                        var lat = position.coords.latitude;
                        map.setCenter([lng, lat]);
                        new AMap.Marker({
                            position: [lng, lat],
                            map: map,
                            title: '当前位置',
                            icon: new AMap.Icon({
                                size: new AMap.Size(32, 32),
                                image: ''
                            })
                        });
                    });
                }
                
                // 加载事件位置标记
                loadEventMarkers();
            }
        }
        
        // 显示用户信息
        function displayUserInfo() {
            const userInfo = window.AuthManager.getUserInfo();
            if (userInfo && userInfo.realName) {
                document.getElementById('userRealName').textContent = userInfo.realName;
            }
        }
        
        // 加载事件位置标记
        async function loadEventMarkers() {
            if (!window.dispatchMap) return;
            
            try {
                const headers = {};
                if (window.AuthManager && window.AuthManager.getAuthHeaders) {
                    Object.assign(headers, window.AuthManager.getAuthHeaders());
                }
                
                const response = await fetch('/ercms/dispatch/api/events', {
                    headers: headers
                });
                if (response.ok) {
                    const result = await response.json();
                    if (result.success) {
                        const events = result.data;
                        
                        // 清除现有标记
                        if (window.eventMarkers) {
                            window.eventMarkers.forEach(marker => marker.setMap(null));
                        }
                        window.eventMarkers = [];
                        
                        // 清除现有响应者标记
                        if (window.responderMarkers) {
                            window.responderMarkers.forEach(marker => marker.setMap(null));
                        }
                        window.responderMarkers = [];
                        
                        // 添加事件标记
                        events.forEach(event => {
                            // 事件位置标记 - 使用Event.location字段
                            if (event.location && event.location.includes(',')) {
                                const parts = event.location.split(',');
                                if (parts.length === 2) {
                                    const lng = Number(parts[0].trim());
                                    const lat = Number(parts[1].trim());
                                    
                                    if (!isNaN(lng) && !isNaN(lat)) {
                                        const eventMarker = new AMap.Marker({
                                            position: [lng, lat],
                                            map: window.dispatchMap,
                                            title: event.title,
                                            icon: new AMap.Icon({
                                                size: new AMap.Size(24, 24),
                                                image: ''
                                            })
                                        });
                                        
                                        // 添加信息窗体
                                        const infoWindow = new AMap.InfoWindow({
                                            content: `
                                                <div style="padding: 10px;">
                                                    <h6>${event.title}</h6>
                                                    <p>状态: ${getStatusText(event.status)}</p>
                                                    <p>位置: ${event.location || '未知'}</p>
                                                    <button onclick="viewEvent(${event.id})" style="background: #007bff; color: white; border: none; padding: 5px 10px; border-radius: 3px; cursor: pointer;">查看详情</button>
                                                </div>
                                            `
                                        });
                                        
                                        eventMarker.on('click', function() {
                                            infoWindow.open(window.dispatchMap, eventMarker.getPosition());
                                        });
                                        
                                        window.eventMarkers.push(eventMarker);
                                        
                                        // 异步加载该事件的响应者位置
                                        loadEventResponderLocations(event.id, window.dispatchMap, lat, lng);
                                    }
                                }
                            }
                        });
                    }
                }
            } catch (error) {
                console.error('加载事件标记失败:', error);
            }
        }

        // 加载事件响应者位置
        async function loadEventResponderLocations(eventId, map, eventLat, eventLng) {
            try {
                const headers = {};
                if (window.AuthManager && window.AuthManager.getAuthHeaders) {
                    Object.assign(headers, window.AuthManager.getAuthHeaders());
                }
                
                const response = await fetch(`/ercms/api/events/${eventId}/all-responder-locations`, {
                    headers: headers
                });
                
                if (response.ok) {
                    const result = await response.json();
                    if (result.success && result.data) {
                        const responderLocations = result.data;
                        if (responderLocations && responderLocations.length > 0) {
                            responderLocations.forEach(locationInfo => {
                                if (locationInfo.location && locationInfo.location.includes(',')) {
                                    const parts = locationInfo.location.split(',');
                                    if (parts.length === 2) {
                                        const responderLng = Number(parts[0].trim());
                                        const responderLat = Number(parts[1].trim());
                                        
                                        if (!isNaN(responderLat) && !isNaN(responderLng) &&
                                            (Math.abs(responderLat - eventLat) > 0.0001 || Math.abs(responderLng - eventLng) > 0.0001)) {
                                            
                                            // 响应者位置标记（蓝色）
                                            const responderMarker = new AMap.Marker({
                                                position: [responderLng, responderLat],
                                                map: map,
                                                title: `${locationInfo.responderName}的位置`,
                                                icon: new AMap.Icon({
                                                    size: new AMap.Size(20, 20),
                                                    image: ''
                                                })
                                            });
                                            
                                            // 响应者位置信息窗体
                                            const responderInfoWindow = new AMap.InfoWindow({
                                                content: `
                                                    <div style="padding: 8px;">
                                                        <h6>${locationInfo.responderName}的位置</h6>
                                                        <p>用户名: ${locationInfo.responderUsername}</p>
                                                        <p>坐标: ${responderLng.toFixed(4)}, ${responderLat.toFixed(4)}</p>
                                                        <p>更新时间: ${new Date(locationInfo.updateTime).toLocaleString('zh-CN')}</p>
                                                    </div>
                                                `
                                            });
                                            
                                            responderMarker.on('click', function() {
                                                responderInfoWindow.open(map, responderMarker.getPosition());
                                            });
                                            
                                            // 将响应者标记也添加到标记数组中
                                            if (!window.responderMarkers) {
                                                window.responderMarkers = [];
                                            }
                                            window.responderMarkers.push(responderMarker);
                                        }
                                    }
                                }
                            });
                        }
                    }
                }
            } catch (error) {
                console.error('获取响应者位置失败:', error);
            }
        }

        // 加载事件列表
        async function loadEvents() {
            try {
                const headers = {};
                if (window.AuthManager && window.AuthManager.getAuthHeaders) {
                    Object.assign(headers, window.AuthManager.getAuthHeaders());
                }
                
                const response = await fetch('/ercms/dispatch/api/events', {
                    headers: headers
                });
                if (response.ok) {
                    const result = await response.json();
                    if (result.success) {
                        events = result.data;
                        await renderEvents();
                    } else {
                        console.error('加载事件失败：', result.message);
                    }
                } else {
                    console.error('加载事件失败');
                }
            } catch (error) {
                console.error('加载事件失败：', error);
            }
        }

        // 坐标反解为地址
        async function reverseGeocode(lng, lat) {
            if (!lng || !lat) return '';
            
            try {
                return new Promise((resolve, reject) => {
                    AMap.plugin('AMap.Geocoder', function() {
                        const geocoder = new AMap.Geocoder();
                        geocoder.getAddress([lng, lat], (status, result) => {
                            if (status === 'complete' && result.info === 'OK') {
                                resolve(result.regeocode.formattedAddress);
                            } else {
                                resolve('');
                            }
                        });
                    });
                });
            } catch (error) {
                console.error('坐标反解失败:', error);
                return '';
            }
        }

        // 处理位置信息
        async function processLocation(location) {
            if (!location) return '未知地点';
            
            // 检查是否是坐标格式 (lng,lat)
            const coordMatch = location.match(/^([-\d.]+),([-\d.]+)$/);
            if (coordMatch) {
                const lng = parseFloat(coordMatch[1]);
                const lat = parseFloat(coordMatch[2]);
                const address = await reverseGeocode(lng, lat);
                return address || location;
            }
            
            return location;
        }

        // 渲染事件列表
        async function renderEvents() {
            const container = document.getElementById('eventsList');
            let filteredEvents = events;
            
            if (currentFilter) {
                filteredEvents = events.filter(event => event.status === currentFilter);
            }
            
            if (filteredEvents.length === 0) {
                container.innerHTML = `
                    <div class="text-center text-muted py-4">
                        <i class="bi bi-inbox" style="font-size: 3rem;"></i>
                        <p class="mt-2">暂无事件</p>
                    </div>
                `;
                return;
            }
            
            // 处理每个事件的位置信息
            let eventsHtml = '';
            for (const event of filteredEvents) {
                const processedLocation = await processLocation(event.location);
                eventsHtml += `
                    <div class="event-item priority-${getPriorityClass(event.priority)}">
                        <div class="row align-items-center">
                            <div class="col-md-8">
                                <h6 class="mb-1">${event.title}</h6>
                                <p class="text-muted mb-1">${processedLocation}</p>
                                <small class="text-muted">
                                    <i class="bi bi-clock"></i> ${formatDateTime(event.startTime)}
                                </small>
                            </div>
                            <div class="col-md-4 text-end">
                                <span class="badge bg-${getStatusColor(event.status)}">${getStatusText(event.status)}</span>
                                ${event.safetyStatus && event.safetyStatus !== 'SAFE' ? 
                                    `<br><span class="badge bg-${getSafetyStatusColor(event.safetyStatus)}">${getSafetyStatusText(event.safetyStatus)}</span>` : 
                                    ''
                                }
                                ${event.supportRequested ? 
                                    `<br><span class="badge bg-warning">支援请求</span>` : 
                                    ''
                                }
                                <div class="mt-1">
                                    <button class="btn btn-sm btn-outline-primary" onclick="viewEvent(${event.id})">
                                        <i class="bi bi-eye"></i> 查看
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                `;
            }
            
            container.innerHTML = eventsHtml;
        }

        // 加载统计数据
        async function loadStatistics() {
            try {
                const headers = {};
                if (window.AuthManager && window.AuthManager.getAuthHeaders) {
                    Object.assign(headers, window.AuthManager.getAuthHeaders());
                }
                
                const response = await fetch('/ercms/dispatch/api/events', {
                    headers: headers
                });
                if (response.ok) {
                    const result = await response.json();
                    if (result.success) {
                        const events = result.data;
                        document.getElementById('pendingCount').textContent = 
                            events.filter(e => e.status === 'PENDING').length;
                        document.getElementById('assignedCount').textContent = 
                            events.filter(e => ['ASSIGNED', 'ACCEPTED', 'EN_ROUTE', 'ARRIVED'].includes(e.status)).length;
                        document.getElementById('inProgressCount').textContent = 
                            events.filter(e => ['IN_PROGRESS', 'COMPLETED', 'RETURNING'].includes(e.status)).length;
                        document.getElementById('resolvedCount').textContent = 
                            events.filter(e => ['RESOLVED', 'CLOSED'].includes(e.status)).length;
                    }
                }
            } catch (error) {
                console.error('加载统计数据失败：', error);
            }
        }

        // 加载通知
        function loadNotifications() {
            const container = document.getElementById('notificationsList');
            container.innerHTML = `
                <div class="text-center text-muted py-2">
                    <i class="bi bi-hourglass-split"></i>
                    正在加载通知...
                </div>
            `;
            
            const headers = {};
            if (window.AuthManager && window.AuthManager.getAuthHeaders) {
                Object.assign(headers, window.AuthManager.getAuthHeaders());
            }
            
            fetch('/ercms/dispatch/api/notifications', {
                headers: headers
            })
                .then(response => response.json())
                .then(result => {
                    if (result.success) {
                        renderNotifications(result.data, result.unreadCount);
                    } else {
                        container.innerHTML = `
                            <div class="alert alert-warning">
                                <i class="bi bi-exclamation-triangle"></i>
                                加载通知失败
                            </div>
                        `;
                    }
                })
                .catch(error => {
                    console.error('加载通知失败：', error);
                    container.innerHTML = `
                        <div class="alert alert-danger">
                            <i class="bi bi-x-circle"></i>
                            网络错误
                        </div>
                    `;
                });
        }

        // 渲染通知列表
        function renderNotifications(notifications, unreadCount) {
            const container = document.getElementById('notificationsList');
            
            if (notifications.length === 0) {
                container.innerHTML = `
                    <div class="text-center text-muted py-4">
                        <i class="bi bi-bell-slash" style="font-size: 2rem;"></i>
                        <p class="mt-2">暂无通知</p>
                    </div>
                `;
                return;
            }
            
            container.innerHTML = notifications.map(notification => `
                <div class="notification-item ${notification.status === 'UNREAD' ? 'unread' : ''} mb-2 p-2 border rounded" 
                     onclick="markNotificationAsRead(${notification.id})">
                    <div class="d-flex justify-content-between align-items-start">
                        <div class="flex-grow-1">
                            <h6 class="mb-1">${notification.title}</h6>
                            <p class="text-muted mb-1 small">${notification.message}</p>
                            <small class="text-muted">
                                <i class="bi bi-clock"></i> ${formatDateTime(notification.createdAt)}
                            </small>
                        </div>
                        <div class="ms-2">
                            ${notification.status === 'UNREAD' ? 
                                '<span class="badge bg-danger">未读</span>' : 
                                '<span class="badge bg-secondary">已读</span>'
                            }
                        </div>
                    </div>
                </div>
            `).join('');
            
            // 更新未读通知数量
            updateUnreadCount(unreadCount);
        }

        // 更新未读通知数量
        function updateUnreadCount(count) {
            const badge = document.getElementById('unreadNotificationBadge');
            if (badge) {
                if (count > 0) {
                    badge.textContent = count;
                    badge.style.display = 'inline';
                } else {
                    badge.style.display = 'none';
                }
            }
        }

        // 标记通知为已读
        function markNotificationAsRead(notificationId) {
            const headers = {};
            if (window.AuthManager && window.AuthManager.getAuthHeaders) {
                Object.assign(headers, window.AuthManager.getAuthHeaders());
            }
            
            fetch(`/ercms/dispatch/api/notifications/${notificationId}/read`, {
                method: 'POST',
                headers: headers
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    loadNotifications();
                }
            })
            .catch(error => {
                console.error('标记通知为已读失败：', error);
            });
        }

        // 标记所有通知为已读
        function markAllNotificationsAsRead() {
            const headers = {};
            if (window.AuthManager && window.AuthManager.getAuthHeaders) {
                Object.assign(headers, window.AuthManager.getAuthHeaders());
            }
            
            fetch('/ercms/dispatch/api/notifications/read-all', {
                method: 'POST',
                headers: headers
            })
            .then(response => response.json())
            .then(result => {
                if (result.success) {
                    loadNotifications();
                }
            })
            .catch(error => {
                console.error('标记所有通知为已读失败：', error);
            });
        }

        // 筛选事件
        async function filterEvents() {
            currentFilter = document.getElementById('statusFilter').value;
            await renderEvents();
        }

        // 查看事件详情
        function viewEvent(eventId) {
            window.location.href = `/ercms/dispatch/event/${eventId}`;
        }

        // 刷新数据
        function refreshData() {
            loadEvents();
            loadStatistics();
            loadNotifications();
            loadEventMarkers(); // 刷新地图标记
        }

        // 显示统计报告
        function showStatistics() {
            window.location.href = '/ercms/statistics';
        }

        // 辅助函数
        function getStatusColor(status) {
            const colors = {
                'PENDING': 'warning',
                'ASSIGNED': 'info',
                'ACCEPTED': 'primary',
                'EN_ROUTE': 'primary',
                'ARRIVED': 'primary',
                'IN_PROGRESS': 'primary',
                'COMPLETED': 'success',
                'RETURNING': 'success',
                'RESOLVED': 'success',
                'CLOSED': 'secondary'
            };
            return colors[status] || 'secondary';
        }

        function getStatusText(status) {
            const texts = {
                'PENDING': '待处理',
                'ASSIGNED': '已指派',
                'ACCEPTED': '已接收',
                'EN_ROUTE': '正在前往',
                'ARRIVED': '到达现场',
                'IN_PROGRESS': '开始处理',
                'COMPLETED': '完成任务',
                'RETURNING': '正在返程',
                'RESOLVED': '已解决',
                'CLOSED': '已关闭'
            };
            return texts[status] || status;
        }

        function getPriorityClass(priority) {
            const classes = {
                'HIGH': 'high',
                'MEDIUM': 'medium',
                'LOW': 'low'
            };
            return classes[priority] || 'medium';
        }

        function formatDateTime(dateTime) {
            if (!dateTime) return '';
            const date = new Date(dateTime);
            return date.toLocaleString('zh-CN');
        }

        // 安全状态相关函数
        function getSafetyStatusText(status) {
            const texts = {
                'SAFE': '安全',
                'CAUTION': '注意',
                'DANGER': '危险',
                'SOS': '紧急求助'
            };
            return texts[status] || (status || '未知');
        }

        function getSafetyStatusColor(status) {
            const colors = {
                'SAFE': 'success',
                'CAUTION': 'warning',
                'DANGER': 'danger',
                'SOS': 'danger'
            };
            return colors[status] || 'secondary';
        }

